package com.ailk.kbi.kbirazor.util

import groovy.sql.Sql
import groovy.util.logging.Slf4j;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 数据源池
 * 
 * @author kyunra
 * 
 */
@Slf4j
public class DspDBCP {
	private static Map dsInfoMap = [
		sqlserver:[key:'sqlserver',url:'jdbc:sqlserver://10.191.113.198:14198;databaseName=cqcrm20', user:'sa', password:'Kava14_198', driver:'com.microsoft.sqlserver.jdbc.SQLServerDriver'],
		sqlserver200:[key:'sqlserver200',url:'jdbc:sqlserver://10.191.113.200:14200;databaseName=cqcrm20', user:'sa', password:'Kava14_200', driver:'com.microsoft.sqlserver.jdbc.SQLServerDriver'],
		sqlserver204:[key:'sqlserver204',url:'jdbc:sqlserver://10.191.113.204:14204;databaseName=cqcrm20', user:'sa', password:'Kava14_204', driver:'com.microsoft.sqlserver.jdbc.SQLServerDriver'],
//		db2:[key:'db2',url:'jdbc:db2://10.191.113.153:50000/CQCCDW', user:'cqcrm', password:'MinofDB153', driver:'com.ibm.db2.jcc.DB2Driver']
		db2:[key:'db2',url:'jdbc:db2://10.191.113.144:50000/CQCCDW', user:'cqcrm', password:'stableBABY99', driver:'com.ibm.db2.jcc.DB2Driver'],
		db3:[key:'db3',url:'jdbc:db2://10.191.113.153:50000/CQCCDW', user:'cqcrm', password:'MinofDB153', driver:'com.ibm.db2.jcc.DB2Driver']
	]
	private static Map dsMap = [:]

	private DspDBCP() {
	}
	
	/**
	 * 获取groovy.sql.Sql对象。
	 * @param key
	 * @return
	 */
	public static Sql getSql(String key) {
		(new DspDBCP()).getSqlInstance(key)
	}

	public Sql getSqlInstance(String key) throws SQLException, PropertyVetoException {
		Map map = dsInfoMap.get(key)
		BasicDataSource ds = getDataSource(map)
		log.info(map.url + " : NumActive = " + ds.getNumActive() + "; NumIdle = " + ds.getNumIdle());
		Sql.newInstance(ds.getConnection())
	}

	private synchronized BasicDataSource getDataSource(Map map) throws PropertyVetoException {
		BasicDataSource ds;
		if (dsMap.containsKey(map.key)) {
			ds = dsMap.get(map.key);
		}
		else {
			ds = new BasicDataSource();
			ds.setDriverClassName(map.driver);
			ds.setUrl(map.url);
			ds.setUsername(map.user);
			ds.setPassword(map.password);
			ds.setMaxIdle(5);
			ds.setMinIdle(0);
			ds.setMaxWait(30000);
			ds.setMaxActive(200);
			dsMap.put(map.key, ds);
		}
		ds
	}
}
